using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;

/// <summary>
/// 管理战斗中的牌堆：抽牌堆、弃牌堆、手牌、消耗牌堆
/// </summary>
public class CardManager : MonoBehaviour
{
    [Header("牌堆设置")]
    public int initialHandSize = 5;
    public int maxHandSize = 10;

    [Header("牌堆引用")]
    public List<Card> drawPile = new List<Card>();
    public List<Card> discardPile = new List<Card>();
    public List<Card> hand = new List<Card>();
    public List<Card> exhaustPile = new List<Card>();

    // 系统引用
    private EffectSystem effectSystem;

    // 事件
    public System.Action<List<Card>> OnHandChanged;
    public System.Action<List<Card>> OnDrawPileChanged;
    public System.Action<List<Card>> OnDiscardPileChanged;

    private void Awake()
    {
        effectSystem = FindObjectOfType<EffectSystem>();
        if (effectSystem == null)
        {
            Debug.LogError("EffectSystem not found in scene!");
        }
    }

    /// <summary>
    /// 初始化牌组（战斗开始时调用）
    /// </summary>
    public void InitializeDeck(List<Card> deck)
    {
        drawPile = new List<Card>(deck);
        discardPile.Clear();
        hand.Clear();
        exhaustPile.Clear();

        ShuffleDrawPile();

        // 初始抽牌
        //DrawCard(initialHandSize);
    }

    /// <summary>
    /// 抽牌
    /// </summary>
    public void DrawCard(int number = 1)
    {
        for (int i = 0; i < number; i++)
        {
            if (hand.Count >= maxHandSize)
            {
                Debug.Log("手牌已满，无法抽牌");
                return;
            }

            if (drawPile.Count == 0)
            {
                if (discardPile.Count == 0)
                {
                    Debug.Log("所有牌堆都为空，无法抽牌");
                    return;
                }
                ShuffleDiscardPileToDrawPile();
            }

            Card drawnCard = drawPile[0];
            drawPile.RemoveAt(0);
            hand.Add(drawnCard);

            Debug.Log($"抽到卡牌: {drawnCard.name}");
        }

        // 触发事件
        OnHandChanged?.Invoke(hand);
        Debug.Log($"已触发OnHandChanged事件");
        OnDrawPileChanged?.Invoke(drawPile);
    }

    /// <summary>
    /// 使用卡牌
    /// </summary>
    public void UseCard(Card card, ITarget user, List<ITarget> targets)
    {
        if (!hand.Contains(card))
        {
            Debug.LogError($"尝试使用不在手牌中的卡牌: {card.name}");
            return;
        }

        // 如果是玩家使用卡牌，检查能量
        if (user is PlayerData player)
        {
            if (!player.CanUseCard(card.energyCost))
            {
                Debug.LogWarning($"能量不足，无法使用 {card.name} (需要 {card.energyCost} 点能量)");
                return;
            }

            // 消耗能量
            player.UseEnergy(card.energyCost);
        }

        // 执行卡牌效果
        card.OnUse(user, targets);

        // 从手牌移除
        hand.Remove(card);

        // 根据卡牌类型决定去向（暂时所有卡牌都进入弃牌堆）
        discardPile.Add(card);

        // 触发事件
        OnHandChanged?.Invoke(hand);
        OnDiscardPileChanged?.Invoke(discardPile);

        Debug.Log($"使用卡牌: {card.name}");
    }

    /// <summary>
    /// 结束回合，手牌进入弃牌堆
    /// </summary>
    public void EndTurn()
    {
        discardPile.AddRange(hand);
        hand.Clear();

        OnHandChanged?.Invoke(hand);
        OnDiscardPileChanged?.Invoke(discardPile);

        Debug.Log("回合结束，手牌进入弃牌堆");
    }

    /// <summary>
    /// 将弃牌堆洗入抽牌堆
    /// </summary>
    public void ShuffleDiscardPileToDrawPile()
    {
        drawPile.AddRange(discardPile);
        discardPile.Clear();
        ShuffleDrawPile();

        OnDrawPileChanged?.Invoke(drawPile);
        OnDiscardPileChanged?.Invoke(discardPile);

        Debug.Log("将弃牌堆洗入抽牌堆");
    }

    /// <summary>
    /// 洗抽牌堆
    /// </summary>
    private void ShuffleDrawPile()
    {
        drawPile = drawPile.OrderBy(x => Random.Range(0, 10000)).ToList();
    }

    /// <summary>
    /// 从牌组中移除卡牌（消耗）
    /// </summary>
    public void ExhaustCard(Card card)
    {
        if (hand.Contains(card))
        {
            hand.Remove(card);
            exhaustPile.Add(card);
            OnHandChanged?.Invoke(hand);
        }
        else if (drawPile.Contains(card))
        {
            drawPile.Remove(card);
            exhaustPile.Add(card);
            OnDrawPileChanged?.Invoke(drawPile);
        }
        else if (discardPile.Contains(card))
        {
            discardPile.Remove(card);
            exhaustPile.Add(card);
            OnDiscardPileChanged?.Invoke(discardPile);
        }
    }

    /// <summary>
    /// 获取牌堆信息（用于调试）
    /// </summary>
    public void PrintDeckInfo()
    {
        Debug.Log($"抽牌堆: {drawPile.Count}张, 弃牌堆: {discardPile.Count}张, 手牌: {hand.Count}张, 消耗堆: {exhaustPile.Count}张");
    }
}